//
//  LSVoiceView.m
//  微信播放语音动画
//
//  Created by 中创 on 2019/7/10.
//  Copyright © 2019 中创慧谷. All rights reserved.
//

#import "LSVoiceView.h"
#import "Masonry/Masonry.h"
@interface LSVoiceView()
/// 背景图
@property (nonatomic, strong) UIImageView * voiceImageView;
/// 动态图
@property (nonatomic, strong) UIImageView * voiceStatusImageView;

@end

@implementation LSVoiceView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpSubViews];
    }
    return self;
}
- (void)setUpSubViews{
    [self addSubview:self.voiceImageView];
    [self.voiceImageView addSubview:self.voiceStatusImageView];
    
    [self.voiceImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.equalTo(self);
        make.width.greaterThanOrEqualTo(@(50));
    }];
    [self.voiceStatusImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.voiceImageView.mas_right).offset(-20);
        make.centerY.equalTo(self.voiceImageView.mas_centerY);
    }];
    self.voiceImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickImage:)];
    [self.voiceImageView addGestureRecognizer:tap];
}

- (void)clickImage:(UITapGestureRecognizer *)tap{
    if (self.voiceStatusImageView.highlighted == YES) {
        [self stopAnimation];
    }else{
        [self startAnimation];
    }
    
}

- (void)startAnimation{
    self.voiceStatusImageView.highlighted = YES;
    [self.voiceStatusImageView startAnimating];
}

- (void)stopAnimation{
    self.voiceStatusImageView.highlighted = NO;
    [self.voiceStatusImageView stopAnimating];
}

- (UIImageView *)voiceImageView{
    if (_voiceImageView == nil) {
        _voiceImageView = [UIImageView new];
        [_voiceImageView setImage:[[UIImage imageNamed:@"bg_chat_me"] resizableImageWithCapInsets:UIEdgeInsetsMake(20, 8, 8, 20) resizingMode:UIImageResizingModeStretch]];
    }
    return _voiceImageView;
}
- (UIImageView *)voiceStatusImageView{
    if (_voiceStatusImageView == nil) {
        _voiceStatusImageView = [UIImageView new];
        UIImage *image1 = [UIImage imageNamed:@"icon_voice_sender_1"];
        UIImage *image2 = [UIImage imageNamed:@"icon_voice_sender_2"];
        UIImage *image3 = [UIImage imageNamed:@"icon_voice_sender_3"];
        _voiceStatusImageView.image = image3;
        _voiceStatusImageView.highlightedAnimationImages = @[image1, image2, image3];
        _voiceStatusImageView.animationDuration = 1.5;
        _voiceStatusImageView.animationRepeatCount = NSUIntegerMax;
    }
    return _voiceStatusImageView;
}

@end
